<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('设备编码')">
              <a-input :placeholder="$t('请输入设备编码')" v-model="queryParam.deviceId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('设备名称')">
              <a-input :placeholder="$t('请输入设备名称')" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('设备类型')">
                <a-select v-model="queryParam.type" :placeholder="$t('请选择设备类型')">
                  <a-select-option v-for="(item, i) in deviceTypeList" :key="i" :value="item.type">{{
                    item.type + '(' + item.type_dictText + ')'
                  }}</a-select-option>
                </a-select>
                <!-- <j-dict-select-tag :placeholder="$t('请选择设备类型')" v-model="queryParam.type" dictCode="bis_device_info.type"/> -->
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('绑定项目')">
                <a-select
                  v-model="queryParam.game"
                  show-search
                  :placeholder="$t('请输入绑定项目')"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  :options="gameList"
                  @search="handleSearch"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="8" :sm="24">
              <a-form-item :label="$t('管理状态')">
                <j-dict-select-tag
                  :placeholder="$t('请选择管理状态')"
                  v-model="queryParam.state"
                  dictCode="bis_device_info.state"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="8" :sm="24">
              <a-form-item :label="$t('机号')">
                <a-input :placeholder="$t('请输入机号')" v-model="queryParam.machineNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="8" :sm="24">
              <a-form-item :label="$t('备注')">
                <a-input :placeholder="$t('请输入备注')" v-model="queryParam.comment"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('最后更新时间')">
                <a-date-picker
                  :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="queryParam.updateTime_begin"
                ></a-date-picker>
                <span class="query-group-split-cust"></span>
                <a-date-picker
                  :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="queryParam.updateTime_end"
                ></a-date-picker>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="8" :sm="24">
              <a-form-item :label="$t('在线状态')">
                <j-dict-select-tag
                  :placeholder="$t('请选择在线状态')"
                  v-model="queryParam.onlineFlag"
                  dictCode="onlineFlag"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantId">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.tenantId">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" v-has="'BisDeviceInfoController:export'" icon="download" :loading="exloading" @click="handleExportXls($t('设备信息'))">{{
        $t('导出')
      }}</a-button>
      <a-button v-has="'BisDeviceInfoController:edit'" type="primary" @click="batchAssign">{{ $t('划拨机台') }}</a-button>
      <a-button v-has="'BisDeviceInfoController:edit'" type="primary" @click="batchOpen">{{ $t('批量启用') }}</a-button>
      <a-button v-has="'BisDeviceInfoController:edit'" type="primary" @click="batchClose">{{ $t('批量禁用') }}</a-button>
      <a-button v-has="'BisDeviceInfoController:delete'" type="primary" @click="batchDel">{{$t('批量删除')}}</a-button>
      <a-button type="primary" @click="searchQuery">{{ $t('刷新') }}</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        <i18n path="selected-items" tag="span">
          <a place="items" style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        </i18n>
        <a style="margin-left: 24px" @click="onClearSelected">{{ $t('清空') }}</a>
        <a-checkbox v-has="'BisDeviceInfoController:edit'" v-model="defaultDeviceStart.ivalues" @change="parameterChange" style="float: right">{{
          $t('新设备默认启用')
        }}</a-checkbox>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>
        <span slot="action" slot-scope="text, record">
          <a v-if="record.qrType == 1" @click="handleDevice(record)">{{ $t('设备码') }}</a>
          <a @click="handleEdit(record)" v-has="'BisDeviceInfoController:edit'" style="margin-left: 7px">{{ $t('编辑') }}</a>
          <a-popconfirm v-has="'BisDeviceInfoController:delete'" :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id)">
            <a style="margin-left: 7px">{{ $t('删除') }}</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <device-info-modal ref="modalForm" @ok="modalFormOk"></device-info-modal>
    <batch-assign-modal ref="modalForm1" @ok="modalFormOk"></batch-assign-modal>
    <a-modal
      class="modal_title"
      :title="$t('设备码')"
      :visible="qrVisible"
      @cancel="handleCancel"
      :cancel-text="$t('关闭')"
    >
      <qrcode-model v-if="qrVisible" :info="info" :param="'deviceId'" :paramValue="'id'"></qrcode-model>
      <template slot="footer">
        <a-button type="default" @click="handleCancel">{{ $t('关闭') }}</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import Vue from 'vue'
import moment from 'moment'
import { getAction, putAction, deleteAction, httpAction } from '@/api/manage'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import DeviceInfoModal from './modules/DeviceInfoModal'
import QrcodeModel from './modules/QrcodeModel'
import BatchAssignModal from './modules/BatchAssignModal'

export default {
  name: 'DeviceInfoList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    DeviceInfoModal,
    QrcodeModel,
    BatchAssignModal,
  },
  data() {
    return {
      description: '设备信息管理页面',
      moment,
      // 表头
      columns: [
        {
          title: this.$t('门店编码'),
          align: 'center',
          sorter: true,
          dataIndex: 'tenantId',
        },
        {
          title: this.$t('门店名称'),
          align: 'center',
          dataIndex: 'tenantId_dictText',
        },
        {
          title: this.$t('设备编码'),
          align: 'center',
          dataIndex: 'deviceId',
        },
        {
          title: this.$t('设备名称'),
          align: 'center',
          sorter: true,
          dataIndex: 'name',
        },
        {
          title: this.$t('机号'),
          align: 'center',
          sorter: true,
          dataIndex: 'machineNo',
        },
        {
          title: this.$t('设备类型'),
          align: 'center',
          sorter: true,
          dataIndex: 'type_dictText',
        },
        {
          title: this.$t('设备型号'),
          align: 'center',
          sorter: true,
          dataIndex: 'type',
        },
        {
          title: this.$t('管理状态'),
          align: 'center',
          sorter: true,
          dataIndex: 'state_dictText',
        },
        {
          title: this.$t('在线状态'),
          align: 'center',
          dataIndex: 'onlineFlag_dictText',
        },
        {
          title: this.$t('商品仓库'),
          align: 'center',
          dataIndex: 'store_dictText',
        },
        {
          title: this.$t('绑定商品'),
          align: 'center',
          dataIndex: 'bisDeviceGoodsList',
          customRender:(t,r)=>{
            let str=''
            if(t&&t.length>0){
              str=t[0].goodsInfo.name
            }
            return str
          }
        },
        {
          title: this.$t('实币仓库'),
          align: 'center',
          dataIndex: 'currencyStore_dictText',
        },
        {
          title: this.$t('币报警值'),
          align: 'center',
          dataIndex: 'coinAlert',
        },
        {
          title: this.$t('绑定娱乐项目'),
          align: 'center',
          dataIndex: 'game_dictText',
        },
        {
          title: this.$t('最后更新时间'),
          align: 'center',
          sorter: true,
          dataIndex: 'updateTime',
        },
        {
          title: this.$t('IP地址'),
          align: 'center',
          dataIndex: 'ip',
        },
        {
          title: this.$t('软件版本'),
          align: 'center',
          sorter: true,
          dataIndex: 'softVersion',
        },
        {
          title: this.$t('硬件版本'),
          align: 'center',
          sorter: true,
          dataIndex: 'hardVersion',
        },
        {
          title: this.$t('信号强度'),
          align: 'center',
          dataIndex: 'networkState',
        },
        {
          title: this.$t('备注'),
          align: 'center',
          dataIndex: 'comment',
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/device/bisDeviceInfo/list',
        delete: '/device/bisDeviceInfo/delete',
        deleteBatch: '/device/bisDeviceInfo/deleteBatch',
        exportXlsUrl: '/device/bisDeviceInfo/exportXls',
        importExcelUrl: 'device/bisDeviceInfo/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      deviceTypeList: [],
      qrVisible: false,
      info: {},
      gameList: [],
      selectedRowKeys: [],
      selectionRows: [],
      batchList: [],
      queryParam:{
        tenantId:''
      },
      shops:[],
      tenantId: Vue.ls.get('TENANT_ID'),
      defaultDeviceStart: {
        name: 'defaultDeviceStart',
        ivalue: 1,
        ivalues: true,
        comment: '新设备默认启用',
      },
    }
  },
  created() {
    if(!this.tenantId){
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
    }
    if (this.tenantId) {
      this.columns = this.columns.filter((o) => {
        return o.dataIndex != 'tenantId' && o.dataIndex != 'tenantId_dictText'
      })
    }
    this.$set(this.dictOptions, 'currencyManage', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.handleSearch('')
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {
      this.getParameter()
      getAction('device/bisDeviceInfo/getTypeList', {}).then((res) => {
        if (res.success) {
          this.deviceTypeList = res.result.records
        }
      })
    },
    modalFormOk() {
      this.searchQuery()
    },
    handleDevice(record) {
      this.qrVisible = true
      this.info = record
    },
    handleCancel() {
      this.qrVisible = false
    },
    handleSearch(value) {
      let query = {}
      query.gameInfo = value
      query.pageNo = 1
      query.pageSize = 99
      getAction('/game/bisGame/list', query).then((res) => {
        if (res.success) {
          this.gameList = []
          res.result.records.forEach((r) => {
            this.gameList.push({
              value: r.id,
              label: r.name,
            })
          })
        }
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
      this.batchList = []
      selectionRows.forEach((row) => {
        this.batchList.push(row.id)
      })
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    batchAssign() {
      if (this.batchList.length > 0) {
        this.$refs.modalForm1.edit(this.batchList)
      } else {
        this.$message.warning(this.$t('请选择需要批量修改的商品'))
      }
    },
    batchOpen() {
      if (this.batchList.length > 0) {
        let queryList = []
        this.batchList.forEach((item) => {
          let aa = {}
          aa.id = item
          aa.state = 0
          queryList.push(aa)
        })
        putAction('/device/bisDeviceInfo/updateBatch', queryList).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.searchQuery()
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    batchClose() {
      if (this.batchList.length > 0) {
        let queryList = []
        this.batchList.forEach((item) => {
          let aa = {}
          aa.id = item
          aa.state = 1
          queryList.push(aa)
        })
        putAction('/device/bisDeviceInfo/updateBatch', queryList).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.searchQuery()
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    batchDel: function () {
      let that = this
      if (that.selectedRowKeys.length <= 0) {
        that.$message.warning(that.$t('请先选择要删除的设备'))
      } else {
        let ids = that.selectedRowKeys.join(',')
        that.$confirm({
          title: that.$t('确认'),
          content: that.$t('您确定要将已选择的设备从列表中清空吗？ '),
          okText: that.$t("确定"),
          cancelText: that.$t("取消"),
          onOk: function () {
            that.loading = true
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
                that.onClearSelected()
              } else {
                that.loading = false
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    getParameter() {
      getAction('/bis/bisSysParameter/list', { name: 'defaultDeviceStart' }).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.defaultDeviceStart = res.result.records[0]
            this.defaultDeviceStart.ivalues = this.defaultDeviceStart.ivalue ? true : false
          } else {
            this.defaultDeviceStart = { name: 'defaultDeviceStart', ivalue: 1, comment: '新设备默认启用' }
            this.defaultDeviceStart.ivalues = true
          }
        }
      })
    },
    parameterChange() {
      let that = this,
        querydata = {}
      let url = '',
        method = ''
      if (that.defaultDeviceStart.id) {
        url = '/bis/bisSysParameter/edit'
        method = 'put'
      } else {
        url = '/bis/bisSysParameter/add'
        method = 'post'
      }
      if (that.defaultDeviceStart.ivalues === true) {
        that.defaultDeviceStart.ivalue = 1
      } else {
        that.defaultDeviceStart.ivalue = 0
      }
      querydata = Object.assign({}, that.defaultDeviceStart)
      httpAction(url, querydata, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.getParameter()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    searchReset(){
      this.queryParam={
        tenantId: ''
      }
      this.searchQuery()
    }
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>